# -*- coding: utf-8 -*-
"""
Created on Mon May 11 03:22:52 2020

@author: Farman
"""


import pathlib
import LandsatFileNameParser as parser


work_dir = pathlib.Path('.')
file_name = 'LandsatDataFiles.list'

#------------------------------------------------------------------------------

with open(work_dir / file_name) as f:
    files = f.readlines()

files = [file.rstrip() for file in files]
        
#------------------------------------------------------------------------------

dict_year = {}
dict_path = {}
dict_row = {}

for file in files:
    file_with_path = file
    file = pathlib.Path(file).name
    cells = parser.parse(file)
    cells = cells[3:]
    path, row, year, month, day, *tail = cells
    
    #-------------------------------
    
    d = dict_year.get(year)
    
    if d == None:
        d = [file_with_path]
    else:
        d.append(file_with_path)
        
    dict_year.update({year : d})
    
    #-------------------------------
    
    d = dict_path.get(path)
    
    if d == None:
        d = [file_with_path]
    else:
        d.append(file_with_path)
        
    dict_path.update({path : d})
    
    #-------------------------------
    
    d = dict_row.get(row)
    
    if d == None:
        d = [file_with_path]
    else:
        d.append(file_with_path)
        
    dict_row.update({row : d})
    

#------------------------------------------------------------------------------

keys = list(dict_year.keys())
keys.sort()

lines = []
lines.append('  Year\t| Scenes')
lines.append('-' * 20)

for k in keys:
    lines.append('%6d\t|%6d'%(k, len(dict_year.get(k))))

for line in lines:
    print(line)
    
lines = [line + '\n' for line in lines]

with open('LandsatDataStatic_year.info', 'w') as f:
    f.writelines(lines)
    
#------------------------------------------------------------------------------

keys = list(dict_path.keys())
keys.sort()

lines = []
lines.append('  Path\t| Scenes')
lines.append('-' * 20)

for k in keys:
    lines.append('%6d\t|%6d'%(k, len(dict_path.get(k))))

for line in lines:
    print(line)
    
lines = [line + '\n' for line in lines]

with open('LandsatDataStatic_path.info', 'w') as f:
    f.writelines(lines)

#------------------------------------------------------------------------------

keys = list(dict_row.keys())
keys.sort()

lines = []
lines.append('    Row\t| Scenes')
lines.append('-' * 20)

for k in keys:
    lines.append('%6d\t|%6d'%(k, len(dict_row.get(k))))

for line in lines:
    print(line)

lines = [line + '\n' for line in lines]

with open('LandsatDataStatic_row.info', 'w') as f:
    f.writelines(lines)


#==============================================================================

keys = list(dict_row.keys())
keys.sort()


for k in keys:
    if k < 128:
        continue
    
    files = dict_row.get(k)
    files = [file + '\n' for file in files]
    
    file_name = "LandsatFileStatic_row_%d.list"%k
    
    with open(file_name, 'w') as f:
        f.writelines(files)
    